package de.carcophan.jimdb.gwt.client.view;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

import de.carcophan.jimdb.gwt.client.presenter.SearchPresenter;
import de.carcophan.jimdb.gwt.shared.entites.Tag;

public class MovieTagDialogImpl extends Composite {

   private static MovieTagDialogImplUiBinder uiBinder = GWT.create(MovieTagDialogImplUiBinder.class);

   interface MovieTagDialogImplUiBinder extends UiBinder<Widget, MovieTagDialogImpl> {
   }

   private SearchPresenter presenter;
   private List<Tag> tags;

   @UiField
   TextBox textBox;
   @UiField
   Button submitButton;
   @UiField
   ListBox tagList;

   private ImageResource deleteTagImage;

   private String selectedTag;

   public MovieTagDialogImpl() {
      initWidget(uiBinder.createAndBindUi(this));
      submitButton.setText("add");
   }

   @UiHandler("submitButton")
   public void onSubmit(ClickEvent e) {
      presenter.onSubmitButtonClicked();
   }

   public String getTextBoxValue() {
      return textBox.getValue();
   }

   public void setTags(List<Tag> tags) {
      this.tags = tags;
      tagList.clear();
      for (Tag tag : tags) {
         tagList.addItem(tag.getName());
      }
   }

   public String getSelectedTag() {
      return selectedTag;
   }

   public void setDeleteTagImage(ImageResource deleteTagImage) {
      this.deleteTagImage = deleteTagImage;
   }

   public void setPresenter(SearchPresenter presenter) {
      this.presenter = presenter;
   }

   public void setSelectedTag(Tag tag) {
      if (tag == null) {
         tagList.setSelectedIndex(0);
      } else {
         int index = tags.indexOf(tag);
         tagList.setSelectedIndex(index);
      }
   }

   @UiHandler("tagList")
   public void onTagSelected(ChangeEvent event) {
      selectedTag = tagList.getItemText(tagList.getSelectedIndex());
      presenter.tagSelected();
   }
}
